package cn.lf.android.lawfirm;

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import cn.jpush.android.api.BasicPushNotificationBuilder;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;
import cn.lf.android.lawfirm.utils.BFileUtil;
import cn.lf.android.lawfirm.utils.DebugLog;
import cn.lf.android.lawfirm.utils.SdcardUtil;
import cn.yzl.okhttputils.okhttp.OkHttpUtils;
import cn.yzl.okhttputils.okhttp.cookie.CookieJarImpl;
import cn.yzl.okhttputils.okhttp.cookie.store.PersistentCookieStore;
import okhttp3.OkHttpClient;

import android.app.Activity;
import android.app.Application;
import android.app.Notification;
import android.content.Context;
import android.os.Environment;
import android.telephony.TelephonyManager;
import android.util.Log;

public class MyApplication extends Application {

    public static Context context;
    private static MyApplication application;

    private static List<Activity> activeActivityList;
    private static BaseActivity mCurrentActivity;

    @Override
    public void onCreate() {
        super.onCreate();
        JPushInterface.init(this);
        makeDirs();
        application = this;
        context = getApplicationContext();
        // okhttp初始化
        CookieJarImpl cookieJar = new CookieJarImpl(new PersistentCookieStore(getApplicationContext()));
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .cookieJar(cookieJar)
                //其他配置
                .build();

        OkHttpUtils.getInstance(okHttpClient);
        OkHttpUtils.getInstance().setConnectTimeout(100000,
                TimeUnit.MILLISECONDS);
        //有的请求可能数据 回传比较 慢,比如后台要和微信交互/图片上传,所以这里 读写也要很长时间
        OkHttpUtils.getInstance().setReadTimeout(100000,
                TimeUnit.MILLISECONDS);
        OkHttpUtils.getInstance().setWriteTimeout(100000,
                TimeUnit.MILLISECONDS);
        OkHttpUtils.getInstance().setCertificates();
//        Constants.initialize();

//        DebugLog.e("---------MyApplication启动-------------");
    }

    public static MyApplication getInstance() {
        if (application == null)
            application = new MyApplication();
        return application;
    }

    /**
     * 获取手机存储路径
     *
     * @return
     */
    public String getPath() {
        if (BFileUtil.isCanUseSD()) {
            return Environment.getExternalStorageDirectory() + "/lawfirm";
        } else {
            return SdcardUtil.getPath() + "/lawfirm";
        }
    }

    /**
     * 在Activity的onCreate中注册
     *
     * @param activity
     */
    public static void registActivity(BaseActivity activity) {
        if (activeActivityList == null) {
            activeActivityList = new ArrayList<Activity>();
        }
        activeActivityList.add(activity);
    }

    /**
     * 在Activity的onDestroy中注册
     *
     * @param activity
     */
    public static void removeActivity(BaseActivity activity) {
        if (activeActivityList != null) {
            activeActivityList.remove(activity);
        }
    }

    /**
     * 在Activity的onResume中注册
     *
     * @param activity
     */
    public static void setCurrentActivity(BaseActivity activity) {
        mCurrentActivity = activity;
    }

    /**
     * 在Activity的onResume中注册
     */
    public static BaseActivity setCurrentActivity() {
        return mCurrentActivity;
    }

    public static void finishAllActivity() {
        if (activeActivityList != null) {
            Iterator<Activity> iterator = activeActivityList.iterator();
            while (iterator.hasNext()) {
                iterator.next().finish();
            }
        }
    }

    /**
     * 退出所有activity
     */
    public void exit() {
        try {
            if (activeActivityList != null) {
                // for(Activity a : activities){
                // a.finish();
                // }
                Activity a;
                int aCount = activeActivityList.size();
                for (int i = 0; i < aCount; i++) {
                    a = activeActivityList.get(i);
                    if (a != null) {
                        if (!a.isFinishing()) {
                            a.finish();
                        }
                        a = null;
                    }
                }
                activeActivityList.clear();
            }
        } catch (Exception e) {
            // TODO: handle exception
        } finally {
            // System.exit(0);
        }
    }

    public void restartToLogin() {
        exit();
    }


    public static BaseActivity getmCurrentActivity() {
        return mCurrentActivity;
    }

    /**
     * 获取IMEI号
     */
    public static String getIMEI() {
        TelephonyManager mTelephonyMgr = (TelephonyManager) context
                .getSystemService(Context.TELEPHONY_SERVICE);
        return mTelephonyMgr.getDeviceId();
    }

    File cacheDir;

    private void makeDirs() {
        String CACHE_DIR;
        String DirFileName = "lawfirm";
        if (Environment.MEDIA_MOUNTED.equals(Environment
                .getExternalStorageState())) {//
            Log.e("SD卡路径", Environment.getExternalStorageDirectory() + "");
            CACHE_DIR = Environment.getExternalStorageDirectory() + "/"
                    + DirFileName;
        } else {
            Log.e("非SD卡路径", Environment.getExternalStorageDirectory() + "");
            CACHE_DIR = Environment.getRootDirectory().getAbsolutePath() + "/"
                    + DirFileName;
        }
        cacheDir = new File(CACHE_DIR);
        if (!cacheDir.exists()) {
            cacheDir.mkdirs();
        }
    }

    public String getFilePath() {
        return cacheDir.getPath();
    }


    /**
     * 获取极光注册ID
     *
     * @return
     */
    public String getJPRegistrationID() {
        return JPushInterface.getRegistrationID(getApplicationContext());
    }

    /**
     * 设置推送别名
     */
    public void setJPAlias(String uid) {
        DebugLog.e("推送别名====" + uid);
        JPushInterface.setAlias(application, uid, new TagAliasCallback() {

            @Override
            public void gotResult(int status, String slias, Set<String> tags) {
                if (status == 0) {
                    DebugLog.i("uid推送别名设置成功====");
                    DebugLog.i(slias);
                } else {
                    DebugLog.i("uid推送别名设置失败====");
                }
            }
        });
    }

    public void setJPAlias() {
        JPushInterface.setAlias(application, "", new TagAliasCallback() {

            @Override
            public void gotResult(int status, String slias, Set<String> tags) {
                if (status == 0) {
                    DebugLog.i("推送别名设置成功");
                    DebugLog.i(slias);
                } else {
                    DebugLog.i("推送别名设置失败");
                }
            }
        });
    }

    /**
     * 设置极光推送为默认样式没有声音
     */
    private void setJPNotification() {
        BasicPushNotificationBuilder builder = new BasicPushNotificationBuilder(context);
        builder.notificationFlags = Notification.FLAG_AUTO_CANCEL
                | Notification.FLAG_SHOW_LIGHTS;  //设置为自动消失和呼吸灯闪烁
        builder.notificationDefaults = Notification.DEFAULT_VIBRATE
                | Notification.DEFAULT_LIGHTS;  // 设置为铃声、震动、呼吸灯闪烁都要
        JPushInterface.setDefaultPushNotificationBuilder(builder);
    }
//
//	public static HomeActivity getHomeActivity() {
//		return homeActivity;
//	}
//
//	public static void setHomeActivity(HomeActivity homeActivity) {
//		MyApplication.homeActivity = homeActivity;
//	}
//	public static LoginActivity getLoginActivity() {
//		return loginActivity;
//	}
//
//	public static void setLoginActivity(LoginActivity loginActivity) {
//		MyApplication.loginActivity = loginActivity;
//	}
//	//此方法1.7后已不使用
//	public static MainActivity getMainActivity() {
//		return mainActivity;
//	}
//	//此方法1.7后已不使用
//	public static void setMainActivity(MainActivity mainActivity) {
//		MyApplication.mainActivity = mainActivity;
//	}
//	public static void setIndexActivity(IndexActivity indexActivity) {
//		MyApplication.indexActivity = indexActivity;
//	}
//	public static IndexActivity getIndexActivity() {
//		return indexActivity;
//	}

}
